package com.smart.yun;

import com.alibaba.fastjson.JSONObject;
import com.smart.yun.client.BusWxmpServiceClient;
import com.smart.yun.client.PlatInfoClient;
import com.smart.common.utils.DateUtils;
import com.smart.common.utils.R;
import com.smart.constants.CommonState;
import com.smart.domain.UserInfoDO;
import com.smart.enums.MobileUserEnum;
import com.smart.enums.QrCodeTypeEnum;
import com.smart.enums.ReturnCodeEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * 微信扫一扫,扫码成功回调页面控制类
 */
@Controller
@RequestMapping("/buswx")
public class WxRedirectController {
    private Logger log = LoggerFactory.getLogger(WxRedirectController.class);
    @Autowired
    private BusWxmpServiceClient busWxmpServiceClient;
    @Autowired
    private PlatInfoClient platInfoClient;

    /**
     * 加油站工作人员扫描二维码快速打开派券页面
     *
     * @return
     */
    @RequestMapping(value = "/stationcp")
    public String stationcpRedirectUri(@RequestParam String code, @RequestParam String state) {

        log.info("[wx]code=" + code + ",state=" + state);

        return "redirect:/station-admin/#/DataLoading?code=" + code + "&state=" + state;
    }

    /**
     * 加油站工作人员展示领券码,用户扫一扫快速领取电子券
     *
     * @return
     */
    @RequestMapping(value = "/sendcp")
    public String sendcpRedirectUri(@RequestParam String code, @RequestParam String state) {

        log.info("[wx]code=" + code + ",state=" + state);

        return "redirect:/user-admin/#/DataLoading?code=" + code + "&state=" + state;
    }

    /**
     * 用户出示电子券二维码,门店工作人员扫一扫,快速核销电子券
     *
     * @return
     */
    @RequestMapping(value = "/shopusecp")
    public String shopusecpRedirectUri(@RequestParam String code, @RequestParam String state) {

        log.info("[wx]code=" + code + ",state=" + state);

        return "redirect:/shop-admin/#/DataLoading?code=" + code + "&state=" + state;
    }

    /**
     * 用户扫一扫,扫描门店二维码,快速核销电子券
     *
     * @return
     */
    @RequestMapping(value = "/userusecp")
    public String userusecpRedirectUri(@RequestParam String code, @RequestParam String state) {

        log.info("[wx]code=" + code + ",state=" + state);

        return "redirect:/user-admin/#/DataLoading?code=" + code + "&state=" + state;
    }

    /**
     * 我的卡包
     *
     * @return
     */
    @RequestMapping(value = "/home")
    public String homeRedirectUri(@RequestParam String code, @RequestParam String state) {

        log.info("[wxRedirect]code=" + code + ",state=" + state);
        String[] params = state.split(",");
        if (params.length < 2) {
            return null;
        }
        String appId = params[0];
        String type = params[1];

        R r = busWxmpServiceClient.getOpenIdByCode(code, appId);
        int resultCode = r.getCode();
        if (ReturnCodeEnum.SUCCESS.getCode() != resultCode) {
            return null;
        }
        String data = r.get("data").toString();
        JSONObject jsonObject = JSONObject.parseObject(data);
        String openId = jsonObject.get("openId").toString();
        String subscribeStatus = jsonObject.get("subscribeStatus").toString();
        log.info("[wxRedirect]code换取用户信息，userInfo = " + jsonObject);
        //已关注用户
        if (subscribeStatus.equals(CommonState.YES_STR)) {
            //根据openId 获取用户信息
            UserInfoDO userInfoDO = platInfoClient.selectUserByOpenId(openId);
            log.info("[wxRedirect]已关注用户根据openId获取用户信息");
            if (ObjectUtils.isEmpty(userInfoDO)) {
                userInfoDO = new UserInfoDO();
                userInfoDO.setOpenId(openId);
                userInfoDO.setUserType(MobileUserEnum.USER.getCode());
                userInfoDO.setCreateTime(DateUtils.getNowDateTime());
                userInfoDO.setCreateBy("用户");
                userInfoDO.setUserFlag(CommonState.YES);
                setUserInfoByWxmpJson(userInfoDO, jsonObject);
                platInfoClient.save(userInfoDO);
                log.info("[wxRedirect]用户信息不存在，新增用户信息，返回用户卡包");
                //普通用户，直接返回用户卡包
                return "redirect:/user-admin/#/DataLoading?code=" + code + "&state=" + state + "&subscribeStatus=" + subscribeStatus + "&openId=" + openId;
            }

            //用户通过我的卡包进入
            if (type.equals(QrCodeTypeEnum.HOME.getCode())) {

                if (userInfoDO.getUserType().equals(MobileUserEnum.SHOP_STAFF.getCode())) {
                    //返回门店主页
                    log.info("[wxRedirect]返回门店端我的卡包页面");
                    return "redirect:/shop-admin/#/DataLoading?code=" + code + "&state=" + state + "&subscribeStatus=" + subscribeStatus + "&openId=" + openId;
                }
                if (userInfoDO.getUserType().equals(MobileUserEnum.OIL_STATION.getCode())) {
                    //返回油站主页
                    log.info("[wxRedirect]返回油站端我的卡包页面");
                    return "redirect:/station-admin/#/DataLoading?code=" + code + "&state=" + state + "&subscribeStatus=" + subscribeStatus + "&openId=" + openId;
                }
            }
        }
        //未关注
        log.info("[wxRedirect]返回用户端我的卡包页面");
        return "redirect:/user-admin/#/DataLoading?code=" + code + "&state=" + state + "&subscribeStatus=" + subscribeStatus + "&openId=" + openId;
    }

    /**
     * 根据微信返回的信息更新用户参数
     *
     * @param userInfoDO
     * @param jsonObj
     */
    private void setUserInfoByWxmpJson(UserInfoDO userInfoDO, JSONObject jsonObj) {
        if (jsonObj.containsKey("nickname")) {// 昵称
            try {
                String nickname = jsonObj.getString("nickname");
                userInfoDO.setUserName(nickname);
            } catch (Exception e) {
                userInfoDO.setUserName("新用户");
                log.info("[wxRedirect]获取用户信息异常，msg = " + e.getMessage());
            }
        }
        if (jsonObj.containsKey("nicknameStr")) {// 昵称
            String nicknameStr = jsonObj.getString("nicknameStr");
            userInfoDO.setUserName(nicknameStr);
        }
        if (jsonObj.containsKey("headimgurl")) {// 用户头像
            userInfoDO.setHeadImgUrl(jsonObj.getString("headimgurl"));
        }
    }
}
